#include<iostream>
#include<unistd.h>
#include<string>
#include<pthread.h>

using namespace std;

pthread_mutex_t mtx;
pthread_cond_t cond;

void* control(void* args)
{
    string name = (char*)args;
    while(1)
    {
        cout << "master say: begin work" << endl;
        //pthread_cond_signal:唤醒在条件变量下等待的一个线程
        pthread_cond_signal(&cond);
        sleep(1);
    }
}

void* work(void* args)
{
    int number = *(int*)args;
    delete (int*)args;

    while(1)
    {
        pthread_cond_wait(&cond, &mtx);
        cout << "worker: " << number << " is working..." << endl;
    }
}

#define NUM 3

int main()
{
    //初始化变量
    pthread_mutex_init(&mtx, nullptr);
    pthread_cond_init(&cond, nullptr);
    
    pthread_t master;
    pthread_t worker[NUM];
    pthread_create(&master, nullptr, control, (void*)"master");
    for(int i = 0; i < NUM; i++)
    {
        int* number = new int(i);
        pthread_create(&worker[i], nullptr, work, (void*)number);
    }



    pthread_join(master, nullptr);
    for(int i = 0; i < NUM; i++)
    {
        pthread_join(worker[i], nullptr);
    }

    //销毁变量
    pthread_mutex_destroy(&mtx);
    pthread_cond_destroy(&cond);
    return 0;
}